package com.xinhua.erp.service;

import com.xinhua.erp.pojo.PageResult;
import com.xinhua.erp.pojo.Result;
import com.xinhua.erp.pojo.Stockhouse;
import com.xinhua.erp.repo.StockhouseRepo;
import com.xinhua.erp.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service

@Transactional
public class StockhouseService {

    @Autowired
    private StockhouseRepo stockhouseRepo;
    @Autowired
    private IdWorker idWorker;

    public Result findAll(int page,int size){

        Pageable pageable = PageRequest.of(page-1, size);

        Page<Stockhouse> stockhouses =stockhouseRepo.findAll(pageable);

        return  Result.OK(new PageResult<>(stockhouses.getTotalElements(),stockhouses.getContent()));
    }

    public Result findAll() {

        List<Stockhouse> list = stockhouseRepo.findAll();

        return Result.OK(list);

    }


    public Result findById(long id) {

        return Result.OK(stockhouseRepo.getOne(id));
    }

    public Result save(Stockhouse stockhouse) {

        stockhouse.setId(idWorker.nextId());

        stockhouseRepo.save(stockhouse);

        return Result.OK();
    }

    public Result update(Stockhouse stockhouse) {
       stockhouseRepo.save(stockhouse);
        return Result.OK();
    }

    public Result deleteById(long id) {

        stockhouseRepo.deleteById(id);

        return Result.OK();
    }
}
